package com.zjhn.ds.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zjhn.ds.common.BizResult;
import com.zjhn.ds.domain.dto.pad.StationMonitorDto;
import com.zjhn.ds.domain.entity.erp.ProTaskDetail;
import com.zjhn.ds.domain.entity.jlw.*;
import com.zjhn.ds.mapper.*;
import com.zjhn.ds.param.StationMonitorParam;
import com.zjhn.ds.service.StationMonitorService;
import com.zjhn.ds.utils.CommonUtil;
import com.zjhn.ds.utils.base.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @BelongsProject: ds_jlw
 * @BelongsPackage: com.zjhn.ds.service.impl
 * @Author: sxt
 * @CreateTime: 2023-10-05  13:55
 * @Description:
 * @Version: 1.0
 */
@Service
public class StationMonitorServiceImpl implements StationMonitorService {

    @Resource
    private CommonUtil commonUtil;

    @Resource
    private GroupSpinnerMapper groupSpinnerMapper;

    @Resource
    private GroupStationMapper groupStationMapper;

    @Resource
    private StationMapper stationMapper;

    @Resource
    private AssignTaskMapper assignTaskMapper;

    @Resource
    private SwipeCardInfoMapper swipeCardInfoMapper;


    /**
     * 机台监控页面数据
     * @param param
     * @return
     */
    @Override
    public BizResult<StationMonitorDto> stationMonitor(StationMonitorParam param) {
        List<Station> stations = new ArrayList<>();
        List<StationMonitorDto.StationInfo> list = new ArrayList<>();
        StationMonitorDto res = StationMonitorDto.builder()
                .runnerQty(0)
                .standByQty(0)
                .closeQty(0)
                .taskWarnQty(0)
                .remainOneDayQty(0)
                .remainTwoDayQty(0)
                .list(list)
                .build();

        if (StringUtils.isNotBlank(param.getSpinnerId())) {
            // 查询挡车工组下的工位信息
            List<GroupSpinner> groupSpinners = groupSpinnerMapper.selectList(new QueryWrapper<GroupSpinner>().eq("spinner_id", param.getSpinnerId()));
            if (groupSpinners.size() > 0) {
                Set<String> groupIds = groupSpinners.stream().map(GroupSpinner::getGroupId).collect(Collectors.toSet());
                List<GroupStation> groupStations = groupStationMapper.selectList(new QueryWrapper<GroupStation>().in("group_id", groupIds));
                if (groupStations.size() > 0) {
                    Set<String> stationIds = groupStations.stream().map(GroupStation::getStationId).collect(Collectors.toSet());
                    stations.addAll(stationMapper.selectBatchIds(stationIds));
                }
            }
        } else
            // 车间主任 查询车间下的工位信息
            stations.addAll(stationMapper.selectList(new QueryWrapper<Station>().eq("workshop_id", param.getWorkshopId())));

        if (stations.size() == 0)
            return BizResult.success(res);

        Set<String> stationIds = stations.stream().map(Station::getId).collect(Collectors.toSet());

        // 获取机台当前刷卡信息
        List<SwipeCardInfo> swipeCardInfos = swipeCardInfoMapper.selectList(new QueryWrapper<SwipeCardInfo>().in("station_id", stationIds));
        Map<String, SwipeCardInfo> swipeCardInfoMap = new HashMap<>();
        List<String> assignTaskIds = new ArrayList<>();
        if (swipeCardInfos.size() > 0) {
            swipeCardInfoMap = swipeCardInfos.stream().collect(Collectors.toMap(SwipeCardInfo::getStationId, c -> c));
            assignTaskIds.addAll(swipeCardInfos.stream().map(SwipeCardInfo::getAssignTaskId).collect(Collectors.toList()));
        }

        // 获取刷卡对应的派工任务
        Map<String, AssignTask> assignTaskMap = new HashMap<>();
        if (assignTaskIds.size() > 0) {
            List<AssignTask> assignTasks = assignTaskMapper.selectBatchIds(assignTaskIds);
            assignTaskMap = assignTasks.stream().collect(Collectors.toMap(AssignTask::getTaskDetailId, c -> c));
        }

        Integer runnerCount = 0;
        Integer standByQty = 0;
        Integer closeQty = 0;
        Integer taskWarnQty = 0;
        Integer remainOneDayQty = 0;
        Integer remainTwoDayQty = 0;
        for (Station station : stations) {
            StationMonitorDto.StationInfo build = StationMonitorDto.StationInfo.builder()
                    .stationId(station.getId())
                    .stationCode(station.getStationCode())
                    .stationName(station.getStationName())
                    .status(commonUtil.getStationStatus(station.getId()))
                    .build();
            SwipeCardInfo swipeCardInfo = swipeCardInfoMap.get(station.getId());
            if (swipeCardInfo != null) {
                build.setStationCode(swipeCardInfo.getStyleCode());

                // 计算剩余时间
                AssignTask assignTask = assignTaskMap.get(swipeCardInfo.getProTaskDetailId());
                if (assignTask != null){
                    build.setCompleteQty(assignTask.getCompleteQty());
                    build.setAssignQty(assignTask.getAssignQty());

                    Date date = DateUtil.dateAddMinute(assignTask.getBeginTime(), assignTask.getRequire());
                    if (date.compareTo(new Date()) > 0) {
                        Integer intervalDays = DateUtil.intervalDays(date, new Date());
                        build.setRemainDay(intervalDays);

                        if (intervalDays == 1)
                            remainOneDayQty++;
                        else if (intervalDays == 2)
                            remainTwoDayQty++;
                    }

                    if (assignTask.getCompleteQty().compareTo(assignTask.getAssignQty().multiply(BigDecimal.valueOf(0.8))) >= 0)
                        // 到达派工的80%
                        taskWarnQty++;
                }
            }

            if (build.getStatus() != null && build.getStatus() == 1) runnerCount++;
            else if (build.getStatus() != null && build.getStatus() == 2) standByQty++;
            else closeQty++;

            list.add(build);
        }

        res.setRunnerQty(runnerCount);
        res.setStandByQty(standByQty);
        res.setCloseQty(closeQty);
        res.setTaskWarnQty(taskWarnQty);
        res.setRemainOneDayQty(remainOneDayQty);
        res.setRemainTwoDayQty(remainTwoDayQty);

        // 排序
        if (param.getOrder() == 1)
            // 工位编号
            list = list.stream()
                    .sorted(Comparator.comparing(c -> Integer.parseInt(c.getStationCode().replace("-", ""))))
                    .collect(Collectors.toList());
        else if (param.getOrder() == 2)
            // 机台状态
            list = list.stream()
                    .sorted(Comparator.comparing(StationMonitorDto.StationInfo::getStatus))
                    .collect(Collectors.toList());
        else
            // 剩余时间
            list = list.stream()
                    .sorted(Comparator.comparing(StationMonitorDto.StationInfo::getRemainDay))
                    .collect(Collectors.toList());

        return BizResult.success(res);
    }
}
